<template>
  <div class="order-management-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">订单管理</h2>
      <p class="page-subtitle">管理系统中的所有订单信息</p>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon total">
            <el-icon><List /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-label">总订单数</div>
            <div class="stat-value">{{ orders.length }}</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon pending">
            <el-icon><Clock /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-label">待处理</div>
            <div class="stat-value">{{ pendingCount }}</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon transit">
            <el-icon><Van /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-label">配送中</div>
            <div class="stat-value">{{ transitCount }}</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon completed">
            <el-icon><CircleCheck /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-label">已完成</div>
            <div class="stat-value">{{ completedCount }}</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 筛选和搜索区域 -->
    <el-card class="filter-card" shadow="never">
      <div class="filter-content">
        <div class="filter-left">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索订单ID、用户名或商户"
            prefix-icon="Search"
            clearable
            class="search-input"
          />
          <el-select v-model="statusFilter" placeholder="筛选状态" clearable>
            <el-option label="全部状态" value="" />
            <el-option label="已提交" value="已提交" />
            <el-option label="在配送中" value="在配送中" />
            <el-option label="已送达" value="已送达" />
            <el-option label="已取消" value="已取消" />
          </el-select>
        </div>
        <div class="filter-right">
          <el-button @click="refreshOrders" :loading="loading">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 订单卡片网格 -->
    <div class="orders-grid" v-loading="loading">
      <el-card
        v-for="order in filteredOrders"
        :key="order.OrderID"
        class="order-card"
        shadow="hover"
      >
        <div class="order-card-header">
          <div class="order-id">
            <span class="order-label">订单号</span>
            <span class="order-number">#{{ order.OrderID }}</span>
          </div>
          <div class="order-status">
            <el-tag
              :type="getStatusType(order.OrderStatus)"
              :effect="order.OrderStatus === '已提交' ? 'plain' : 'dark'"
            >
              {{ order.OrderStatus }}
            </el-tag>
          </div>
        </div>

        <div class="order-card-content">
          <div class="order-info-row">
            <div class="order-info-item">
              <el-icon class="info-icon"><Calendar /></el-icon>
              <span class="info-label">下单时间：</span>
              <span class="info-value">{{ formatDate(order.OrderDate) }}</span>
            </div>
          </div>

          <div class="order-info-row">
            <div class="order-info-item">
              <el-icon class="info-icon"><Money /></el-icon>
              <span class="info-label">订单金额：</span>
              <span class="info-value price">¥{{ order.TotalPrice }}</span>
            </div>
          </div>

          <div class="order-info-row" v-if="order.username">
            <div class="order-info-item">
              <el-icon class="info-icon"><User /></el-icon>
              <span class="info-label">用户：</span>
              <span class="info-value">{{ order.username }}</span>
            </div>
          </div>

          <div class="order-info-row" v-if="order.restaurant_name">
            <div class="order-info-item">
              <el-icon class="info-icon"><Shop /></el-icon>
              <span class="info-label">商户：</span>
              <span class="info-value">{{ order.restaurant_name }}</span>
            </div>
          </div>
        </div>

        <div class="order-card-actions">
          <el-button
            v-if="order.OrderStatus === '已提交'"
            type="primary"
            size="small"
            @click="orderInTransit(order.OrderID)"
          >
            <el-icon><Van /></el-icon>
            开始配送
          </el-button>

          <el-button
            v-if="order.OrderStatus === '在配送中'"
            type="success"
            size="small"
            @click="orderDelivered(order.OrderID)"
          >
            <el-icon><CircleCheck /></el-icon>
            确认送达
          </el-button>

          <el-button
            v-if="['已提交', '在配送中'].includes(order.OrderStatus)"
            type="danger"
            size="small"
            @click="cancelOrder(order.OrderID)"
          >
            <el-icon><Close /></el-icon>
            取消订单
          </el-button>

          <el-button
            type="info"
            size="small"
            @click="viewOrderDetails(order)"
          >
            <el-icon><View /></el-icon>
            查看详情
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 空状态 -->
    <div v-if="filteredOrders.length === 0 && !loading" class="empty-state">
      <el-empty description="暂无订单数据">
        <el-button type="primary" @click="refreshOrders">
          刷新数据
        </el-button>
      </el-empty>
    </div>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="订单详情"
      width="600px"
      @close="closeDetailDialog"
    >
      <div class="order-detail-content" v-if="selectedOrder">
        <div class="detail-section">
          <h4>基本信息</h4>
          <div class="detail-grid">
            <div class="detail-item">
              <span class="detail-label">订单号：</span>
              <span class="detail-value">#{{ selectedOrder.OrderID }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">状态：</span>
              <el-tag :type="getStatusType(selectedOrder.OrderStatus)">
                {{ selectedOrder.OrderStatus }}
              </el-tag>
            </div>
            <div class="detail-item">
              <span class="detail-label">下单时间：</span>
              <span class="detail-value">{{ formatDate(selectedOrder.OrderDate) }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">订单金额：</span>
              <span class="detail-value price">¥{{ selectedOrder.TotalPrice }}</span>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from 'element-plus';
import { getAllOrdersApi, cancelOrderApi } from "@/utils/api";
import {
  List,
  Clock,
  Van,
  CircleCheck,
  Search,
  Refresh,
  Calendar,
  Money,
  User,
  Shop,
  Close,
  View
} from '@element-plus/icons-vue';

// 响应式数据
const orders = ref([]);
const loading = ref(false);
const searchKeyword = ref("");
const statusFilter = ref("");
const detailDialogVisible = ref(false);
const selectedOrder = ref(null);

// 计算属性
const pendingCount = computed(() =>
  orders.value.filter(order => order.OrderStatus === '已提交').length
);

const transitCount = computed(() =>
  orders.value.filter(order => order.OrderStatus === '在配送中').length
);

const completedCount = computed(() =>
  orders.value.filter(order => order.OrderStatus === '已送达').length
);

const filteredOrders = computed(() => {
  let filtered = orders.value;

  // 状态筛选
  if (statusFilter.value) {
    filtered = filtered.filter(order => order.OrderStatus === statusFilter.value);
  }

  // 搜索关键词筛选
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase();
    filtered = filtered.filter(order =>
      order.OrderID.toString().includes(keyword) ||
      order.username?.toLowerCase().includes(keyword) ||
      order.restaurant_name?.toLowerCase().includes(keyword) ||
      order.OrderStatus.toLowerCase().includes(keyword)
    );
  }

  return filtered;
});

// 获取订单数据
const fetchOrders = async () => {
  try {
    loading.value = true;
    const res = await getAllOrdersApi();

    if (res && res.orders && Array.isArray(res.orders)) {
      orders.value = res.orders;
    } else {
      console.warn('No orders data found or invalid format:', res);
      orders.value = [];
    }
  } catch (error) {
    console.error('获取订单列表失败:', error);
    ElMessage.error('获取订单列表失败');
    orders.value = [];
  } finally {
    loading.value = false;
  }
};

// 刷新订单列表
const refreshOrders = () => {
  fetchOrders();
};

// 取消订单
const cancelOrder = async (orderId) => {
  try {
    await ElMessageBox.confirm(
      '确定要取消该订单吗？',
      '取消确认',
      {
        confirmButtonText: '确定取消',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    );

    const data = { id: orderId, orderStatus: "已取消" };
    const response = await cancelOrderApi(data);

    if (response.code === 200) {
      ElMessage.success('订单已取消');
      await fetchOrders();
    } else {
      ElMessage.error(response.message || '取消失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error("取消订单失败:", error);
      ElMessage.error('取消订单失败');
    }
  }
};

// 订单配送中
const orderInTransit = async (orderId) => {
  try {
    const data = { id: orderId, orderStatus: "在配送中" };
    const response = await cancelOrderApi(data);

    if (response.code === 200) {
      ElMessage.success('订单状态已更新为配送中');
      await fetchOrders();
    } else {
      ElMessage.error(response.message || '状态更新失败');
    }
  } catch (error) {
    console.error("更新订单状态失败:", error);
    ElMessage.error('状态更新失败');
  }
};

// 订单已送达
const orderDelivered = async (orderId) => {
  try {
    const data = { id: orderId, orderStatus: "已送达" };
    const response = await cancelOrderApi(data);

    if (response.code === 200) {
      ElMessage.success('订单状态已更新为已送达');
      await fetchOrders();
    } else {
      ElMessage.error(response.message || '状态更新失败');
    }
  } catch (error) {
    console.error("更新订单状态失败:", error);
    ElMessage.error('状态更新失败');
  }
};

// 查看订单详情
const viewOrderDetails = (order) => {
  selectedOrder.value = order;
  detailDialogVisible.value = true;
};

// 关闭详情对话框
const closeDetailDialog = () => {
  selectedOrder.value = null;
};

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    '已提交': 'warning',
    '在配送中': 'primary',
    '已送达': 'success',
    '已取消': 'danger'
  };
  return statusMap[status] || 'info';
};

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '-';
  return new Date(dateStr).toLocaleString('zh-CN');
};

// 组件挂载时获取数据
onMounted(() => {
  fetchOrders();
});
</script>

<style lang="less" scoped>
.order-management-page {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.page-header {
  margin-bottom: 24px;

  .page-title {
    font-size: 24px;
    font-weight: 600;
    color: #303133;
    margin: 0 0 8px 0;
  }

  .page-subtitle {
    color: #909399;
    margin: 0;
    font-size: 14px;
  }
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.stat-card {
  border: none;
  border-radius: 12px;
  overflow: hidden;

  :deep(.el-card__body) {
    padding: 20px;
  }

  .stat-content {
    display: flex;
    align-items: center;
    gap: 16px;
  }

  .stat-icon {
    width: 50px;
    height: 50px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    color: white;

    &.total {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    }

    &.pending {
      background: linear-gradient(135deg, #e6a23c 0%, #f56c6c 100%);
    }

    &.transit {
      background: linear-gradient(135deg, #409eff 0%, #36cfc9 100%);
    }

    &.completed {
      background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
    }
  }

  .stat-info {
    flex: 1;

    .stat-label {
      font-size: 14px;
      color: #909399;
      margin-bottom: 4px;
    }

    .stat-value {
      font-size: 24px;
      font-weight: 600;
      color: #303133;
    }
  }
}

.filter-card {
  margin-bottom: 20px;
  border: none;

  :deep(.el-card__body) {
    padding: 16px 20px;
  }
}

.filter-content {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .filter-left {
    display: flex;
    gap: 16px;
    align-items: center;

    .search-input {
      width: 300px;
    }
  }

  .filter-right {
    display: flex;
    gap: 12px;
  }
}

.orders-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.order-card {
  border: none;
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-4px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
  }

  :deep(.el-card__body) {
    padding: 20px;
  }
}

.order-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;

  .order-id {
    .order-label {
      font-size: 12px;
      color: #909399;
      display: block;
      margin-bottom: 4px;
    }

    .order-number {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
    }
  }
}

.order-card-content {
  margin-bottom: 16px;

  .order-info-row {
    margin-bottom: 12px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .order-info-item {
    display: flex;
    align-items: center;
    gap: 8px;

    .info-icon {
      color: #909399;
      font-size: 14px;
      flex-shrink: 0;
    }

    .info-label {
      font-size: 14px;
      color: #909399;
      min-width: 70px;
    }

    .info-value {
      font-size: 14px;
      color: #606266;

      &.price {
        font-weight: 600;
        color: #f56c6c;
      }
    }
  }
}

.order-card-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
  padding-top: 16px;
  border-top: 1px solid #f0f2f5;
  flex-wrap: wrap;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  background: white;
  border-radius: 12px;
}

.order-detail-content {
  .detail-section {
    margin-bottom: 20px;

    h4 {
      margin: 0 0 16px 0;
      color: #303133;
      font-size: 16px;
      font-weight: 600;
    }
  }

  .detail-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 16px;
  }

  .detail-item {
    .detail-label {
      font-size: 14px;
      color: #909399;
      margin-right: 8px;
    }

    .detail-value {
      font-size: 14px;
      color: #606266;

      &.price {
        font-weight: 600;
        color: #f56c6c;
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

// 响应式设计
@media (max-width: 768px) {
  .order-management-page {
    padding: 16px;
  }

  .stats-cards {
    grid-template-columns: repeat(2, 1fr);
    gap: 16px;
  }

  .filter-content {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;

    .search-input {
      width: 100%;
    }
  }

  .orders-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .order-card-actions {
    flex-direction: column;

    .el-button {
      width: 100%;
    }
  }

  .detail-grid {
    grid-template-columns: 1fr;
  }
}
</style>
